import {
	login,
	loginOut
} from '@/api/login/login.js'
const state = {
	hasLogin: false, //是否登录
	token: '',
	userId: '' //用户id
	// userInfo: {}
}
const mutations = {
	SET_TOKEN: (state, user) => {
		state.token = user.token
		state.hasLogin = true
		state.userId = user.id
		uni.setStorage({
			key: 'userInfo',
			data: user
		})
	},
	LOGINOUT(state) {
		state.token = ''
		state.hasLogin = false
		state.userId = ''
		console.log("退出登录=");
		uni.removeStorage({
			key: 'userInfo'
		})
		uni.clearStorage();
	}
}
const actions = {
	Login({
		commit
	}, userInfo) {
		return new Promise((resolve, reject) => {
			uni.showLoading({
				title: '登录中...'
			});
			let msg = {
				logType: userInfo.logType,
				username: userInfo.username,
				password: userInfo.password || null,
				code: userInfo.code || null,
				openid: userInfo.openid || null,
				nickname: userInfo.nickname || null, //微信名称
				headimgurl: userInfo.headimgurl || null //微信头像
			}
			// console.log("登录参数=>",userInfo);
			login(msg).then(res => {
				// console.log("登录成功", res)
				if (res.code == 0) {
					let user = {
						token: res.data.token,
						hasLogin: true,
						userId: res.data.id,
						audit:res.data.audit
					}
					// console.log("---", user);
					commit('SET_TOKEN', user)
					uni.hideLoading();
					resolve()
				} else {
					uni.hideLoading();
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 850
					});
				}
			})
		}).catch(err => {
			console.log("登录失败", err);
			uni.hideLoading()
			reject(err)
		})
	},
	// 退出登录
	Logout({
		commit
	}, token) {
		return new Promise((resolve) => {
			loginOut({
				token: token
			}).then((res) => {
				console.log("退出登录成功", res);
				commit('LOGINOUT')
				resolve(res)
			}).catch((err) => {
				console.log("退出登录失败", err);
				reject(err)
			})
		})
	}
}
export default {
	namespaced: true,
	state,
	mutations,
	actions
}